//
//  XS_VideoFullVC.swift
//  XueDao
//
//  Created by 韩云智 on 2021/1/14.
//

import UIKit
import RxSwift
import RxCocoa
import AliyunPlayer

class XS_VideoFullVC: XS_BaseVC {
    deinit {
        player?.stop()
        player?.destroy()
        player?.delegate = nil
    }
    
    var playerUrl: URL?
    
    private lazy var player = AliPlayer()
    private lazy var botView = UIView()
    
    private lazy var playBtn = XS_NoHighlightBtn()
    private lazy var timeLab = UILabel.xsLabel(size: .scale*10, fontName: .regular, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0))
    private lazy var slider = UISlider()
    
    override func upConfig() {
        orientations = .landscape
        modalPresentationStyle = .fullScreen
        modalTransitionStyle = .crossDissolve
        isStatusBarBlack = false
    }

    override func upView() {
        view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        
        let imgV = UIImageView()
        view.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        
        botView.isHidden = true
        view.addSubview(botView)
        botView.snp.makeConstraints({
            $0.left.bottom.right.equalToSuperview()
            $0.height.equalTo(.scale*40)
        })
        
        playBtn.setBackgroundImage(UIImage(named: "编组播放"), for: .normal)
        playBtn.setBackgroundImage(UIImage(named: "icon_16px_暂停_1"), for: .selected)
        botView.addSubview(playBtn)
        playBtn.snp.makeConstraints({
            $0.width.height.equalTo(.scale*16)
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*16)
        })
        
        
        slider.maximumValue = 1
        slider.maximumTrackTintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.39)
        slider.minimumTrackTintColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        slider.setThumbImage(getImg(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)), for: .normal)
        botView.addSubview(slider)
        slider.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*48)
            $0.right.equalTo(-.scale*112)
        })
        
        botView.addSubview(timeLab)
        timeLab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(slider.snp.right).offset(.scale*8)
        })
        
        loadHCustomBar()
        
        guard let player = player else { return }
        player.isAutoPlay = true
        player.isLoop = false
        player.scalingMode = .init(0)
        player.playerView = imgV
        player.delegate = self
        
        playBtn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let select = self?.playBtn.isSelected else { return }
                if select {
                    player.pause()
                } else if player.duration > player.currentPosition {
                    player.start()
                } else {
                    player.prepare()
                    player.start()
                }
            }).disposed(by: disposeBag)
        slider.rx.controlEvent(.touchDown).asDriver()
            .drive(onNext: { _ in
                player.pause()
            }).disposed(by: disposeBag)
        slider.rx.controlEvent([.touchUpInside, .touchUpOutside, .touchDownRepeat, .touchCancel]).asDriver()
            .drive(onNext: { [weak self, weak player] _ in
                guard let `self` = self, let player = player else { return }
                let position = Int64(Float(player.duration) * self.slider.value)
                player.seek(toTime: position, seekMode: .init(0))
                player.start()
            }).disposed(by: disposeBag)
        slider.rx.controlEvent(.valueChanged).asDriver()
            .drive(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                let position = Int64(Float(player.duration) * self.slider.value)
                self.onCurrentPositionUpdate(player, position: position)
            }).disposed(by: disposeBag)
        

        let source = AVPUrlSource()
        source.playerUrl = playerUrl
        //设置播放源
        player.setUrlSource(source)
        //准备播放
        player.prepare()
        
    }
    
    func getImg(_ color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 12, height: 12)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.addArc(center: CGPoint(x: 6, y: 6), radius: 6, startAngle: 0, endAngle: .pi*2, clockwise: true)
        context?.setFillColor(color.cgColor)
        context?.fillPath()
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
    
    override func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        player?.destroy()
        dismiss(animated: true)
        return false
    }
}

extension XS_VideoFullVC: AVPDelegate {
    func onPlayerStatusChanged(_ player: AliPlayer!, oldStatus: AVPStatus, newStatus: AVPStatus) {
        switch newStatus {
        case .init(4), .init(5), .init(6): // 播放完成
            playBtn.isSelected = false
        case .init(3): // 正在播放
            playBtn.isSelected = true
        case .init(2): // 准备完成
            botView.isHidden = false
        default: break
        }
    }
    
    func onCurrentPositionUpdate(_ player: AliPlayer!, position: Int64) {
        timeLab.text = "\(position.toTimeStr())/\(player.duration.toTimeStr())"
        let progress = CGFloat(position)/CGFloat(player.duration)
        slider.value = Float(progress)
        NotificationCenter.default.post(name: Notification.Name("XS_VideoProgress"), object: progress)
    }
}
